package com.hd.trans.extension


/**
 * @author       qianjujun
 * @email        qianjujun@163.com
 * @createTime  2021/1/7 14:23
 * @describe
 */


fun <T> ArrayList<T>.takeFirst() : T? =
     takeIf { isNotEmpty() }?.get(0)

fun <T> ArrayList<T>.compatRemoveIf(filter: (T) -> Boolean):Boolean{
     val listTemp = ArrayList(this)
     this.clear()
     listTemp.forEach {
          if(!filter(it)){
               this.add(it)
          }
     }
     return listTemp.size != this.size
}

fun <T> ArrayList<T>.removeFirstIf() : T? {
     return if (size == 0)
          null
     else
          removeAt(0)
}

fun <T> ArrayList<T>.filterArrayList(filter: (T) -> Boolean):ArrayList<T> {
     val newList = arrayListOf<T>()
     for (t in this){
          if (filter(t)) {
               newList.add(t)
          }
     }
     return newList
}

fun <T> List<T>.compatRemovedIf(filter: (T) -> Boolean): List<T> {
     return if (this is ArrayList) {
          compatRemoveIf(filter)
          this
     } else {
          val listTemp = ArrayList(this)
          listTemp.compatRemoveIf(filter)
          listTemp
     }
}

/**
 * 如果集合中有且仅有一个元素，则返回该元素，否则返回null
 */
val <T> List<T>.onlyOne: T? get() = if (this.size == 1) this[0] else null

fun <T> LinkedHashSet<T>.compatRemoveIf(filter: (T) -> Boolean): Boolean {
     val setTemp = LinkedHashSet(this)
     this.clear()
     setTemp.forEach {
          if (!filter(it)) {
               this.add(it)
          }
     }
     return setTemp.size != this.size
}

fun <T, D> LinkedHashMap<T, D>.sortWith(comparator: Comparator<T>) {
     val keys = this.keys.toMutableList()
     keys.sortWith(comparator)
     //复制一份
     val temp = LinkedHashMap<T, D>(this)
     this.clear()
     keys.forEach {
          temp[it]?.let { d ->
               this[it] = d
          }
     }
}

fun <T, D> Map<T, D>.firstOrNull(): Map.Entry<T, D>? {
     return entries.firstOrNull()
}

fun <T, D> Map<T, D>.first(): Map.Entry<T, D> {
     return entries.first()
}

fun <T> Collection<T>?.isNotNullOrEmpty(): Boolean {
     if (this == null)
          return false
     if (this.isEmpty())
          return false
     return true
}

inline fun <reified T> Collection<T>?.toTypedArrayCompat(start: Int = 0, end: Int = -1): Array<T> {
     if (this.isNullOrEmpty())
          return emptyArray()

     if (start >= this.size)
          return emptyArray()

     var mStart = start
     var mEnd = end

     if (mStart < 0)
          mStart = 0

     if (mEnd < 0 || mEnd > this.size)
          mEnd = this.size

     val arraySize = mEnd - mStart

     if (arraySize <= 0)
          return emptyArray()

     val array = arrayOfNulls<T>(arraySize)

     var arrayPos = 0
     forEachIndexed { index, t ->
          if (index in mStart until mEnd) {
               array[arrayPos] = t
               arrayPos++
          }
     }

     return array as Array<T>
}


